import { Effect, Schedule } from "effect";

function mockRequest(): boolean {
  const n = Math.random() < 0.2;

  if (n) {
    console.log("succeed");
  } else {
    console.log("failure");
  }
  return n;
}
const mockTask = Effect.gen(function* () {
  yield* Effect.fail("failure");
  yield* Effect.fail("failure");
  yield* Effect.succeed("succeed");
  return "Complete!";
});

// Simulates an effect with possible failures
const task = Effect.async<string, Error>((resume) => {
  resume(
    mockRequest()
      ? Effect.succeed("Complete!")
      : Effect.fail(new Error("Failed")),
  );
});

// Define a repetition policy using a fixed delay between retries
const policy = Schedule.fixed("1000 millis");

const repeated = Effect.retry(task, policy);

Effect.runPromise(repeated).catch(console.error).then(console.log);
/*
Output:
failure
failure
failure
success
yay!
*/
